package main
import (
	"fmt"
	"github.com/BurntSushi/toml"
        "io"
	"mime/multipart"
        "io/ioutil"
	"os"
	"os/exec"
        "log"
	"strings"
	"net/http"
	"time"
	"bytes"
)
type Info struct {
        Fdir           string
        HttpUrl        string
}
var configData Info=Info{}
var httpLog *log.Logger
func ReadConf() bool {
        fp, err := os.Open("./conf.toml")
        if err != nil {
                fmt.Printf("open  error\n")
                return false
        }
        fcontent, err := ioutil.ReadAll(fp)
        if err != nil {
                fmt.Printf("ReadAll error\n")
                return false
        }
        err = toml.Unmarshal(fcontent, &configData)
        if err != nil {
                fmt.Printf("Unmarshal error\n")
                return false
        }
        return true
}
func postFile(filename string, buf *bytes.Buffer,newfilename string) error {
	defer func() {
                if err:=recover();err!=nil {
                        httpLog.Println(err)
                }
        }()
	httpLog.Printf("Begin to postFile for %s.",filename)
	buf.Reset()
	bodyWriter:=multipart.NewWriter(buf)
	fileWriter,err:=bodyWriter.CreateFormFile("uploadfile",newfilename)
	if err!=nil {
		httpLog.Println("error writing to buffer")
		return err
	}
	fh,err:=os.Open(filename)
	if err!=nil {
		httpLog.Println("error opening file")
		return err
	}
	_,err=io.Copy(fileWriter,fh)
	if err!=nil {
		return err
	}
	contentType:=bodyWriter.FormDataContentType()
	bodyWriter.Close()
	resp,err:=http.Post(configData.HttpUrl,contentType,buf)
	if err!=nil  {
		httpLog.Printf("error post content to http server!\n")
		return err
	}
	defer resp.Body.Close()
	resp_body,err:=ioutil.ReadAll(resp.Body)
	if err!=nil {
		return err
	}
	httpLog.Printf(string(resp_body))
	httpLog.Printf("End to postFile for %s.",filename)
	return nil
}
func main(){
	result:=ReadConf()
	if result!=true {
		fmt.Printf("Read configdata error!\n")
		return
	}
        logFile, err := os.Create("./upload.log")
        defer logFile.Close()
        if err != nil {
                fmt.Printf("Open file error!\n")
        }
	httpLog= log.New(logFile, "[Info]", log.Ldate|log.Ltime|log.Lshortfile)
	buf:=new(bytes.Buffer)
	buft:=new(bytes.Buffer)
	timer1:=time.NewTicker(time.Duration(100)*time.Millisecond)
	for {
		select {
		case<-timer1.C:
			buf.Reset()
			bsh := fmt.Sprintf("ls  %s/*.ts",configData.Fdir)
		        cmd := exec.Command("/bin/bash", "-c", bsh)
        		cmd.Stdout = buf
			cmd.Stderr = buf
        		cmd.Run()
			res := strings.Replace(buf.String(), "\n", "", -1)
			if !strings.Contains(res,"No such file or directory") {
				buf.Reset()
				bsh :=fmt.Sprintf("ls %s/*.m3u8",configData.Fdir)
				cmd :=exec.Command("/bin/bash","-c",bsh)
				cmd.Stdout =buf
				err:=cmd.Run()
				if err!=nil {
					httpLog.Printf("no m3u8 file exist!\n")
					continue
				}
				indexname := strings.Replace(buf.String(), "\n", "", -1)
				err=postFile(indexname,buft,"index.m3u8")
				if err!=nil {
					httpLog.Printf("error postFile index.m3u8!\n")
					continue
				}
				dir_list,err:=ioutil.ReadDir(configData.Fdir)
				if err!=nil {
					httpLog.Printf("error readDir!\n")
					continue
				}
				for _,v:=range dir_list {
					filename:=v.Name()
					if strings.Contains(filename,".ts")==true {
						httpLog.Println(filename)
						err:=postFile(configData.Fdir+"/"+filename,buft,filename)
						if err!=nil {
							httpLog.Printf("error postFile for %s.\n",filename)
						}
						err=os.Remove(configData.Fdir+"/"+filename)
						if err!=nil {
							httpLog.Println(err)
						}
        				}
				}
			}
		}
	}
}						
					

















								
				
	
